package com.aloha.springframework.beans.factory.support;

import cn.hutool.core.util.StrUtil;
import com.aloha.springframework.beans.BeansException;
import com.aloha.springframework.beans.factory.config.BeanDefinition;
import com.aloha.springframework.beans.factory.DisposableBean;

import java.lang.reflect.Method;

/**
 * @author DaiZhiHeng
 * @description 用于适配实现了DisposableBean接口或者提供销毁方法的Bean
 * @date 2023/7/1 22:33
 */
public class DisposableBeanAdapter implements DisposableBean {

    // 拥有销毁方法的对象
    private final Object bean;
    private final String beanName;
    // 销毁方法的名字
    private final String destroyMethodName;

    public DisposableBeanAdapter(Object bean, String beanName, BeanDefinition beanDefinition) {
        this.bean = bean;
        this.beanName = beanName;
        this.destroyMethodName = beanDefinition.getDestroyMethodName();
    }

    @Override
    public void destroy() throws Exception {

        // 实现 DisposableBean 接口的bean
        if (bean instanceof DisposableBean) {
            ((DisposableBean) bean).destroy();
        }

        // destroy-method
        if (StrUtil.isNotEmpty(destroyMethodName)
                && !(bean instanceof DisposableBean && "destroy".equals(destroyMethodName))) {
            try {
                Method destroyMethod = bean.getClass().getMethod(destroyMethodName);
                destroyMethod.invoke(bean);
            } catch (Exception e) {
                throw new BeansException("在 [" + beanName + "] 中未找到名为 [" + destroyMethodName + "] 的销毁方法");
            }
        }

    }
}
